package com.live.shop.home.prologue;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.aliyun.AliyunTtsUtil;
import com.live.shop.home.AudioFileListActivity;
import com.live.shop.home.setting.PermissionActivity;
import com.live.shop.model.AudioFileModel;
import com.live.shop.model.PrologueModel;
import com.live.shop.model.UserModel;
import com.live.shop.sql.PrologueListDatabase;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.FileUtils;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.TtsMessageEvent;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastBottomUtils;
import com.live.shop.view.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

public class AddPrologueActivity extends BaseActivity {
    ImageButton add_prologue_back;
    TextView add_prologue_title;
    EditText add_prologue_edittext;
    TextView add_prologue_save;
    
    TextView add_prologue_type;
    TextView add_prologue_status;
    TextView add_prologue_inputnum;
    
    TextView add_prologue_sound_start;
    TextView add_prologue_sound_stop;
    TextView add_prologue_sound_ai;
    TextView add_prologue_sound_local;
    TextView add_prologue_sound_listen;

    //播放器
    MediaPlayer mediaPlayer;
    //录音
    MediaRecorder mediaRecorder;
    UserModel userModel;
    //播放状态
    int PlayStatus = 0;
    //数据类型
    int DataType = 0;
    PrologueModel prologueModel;
    String fileDir="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_prologue);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);
        //首先要在你要接受EventBus的界面注册，这一步很重要
        EventBus.getDefault().register(this);

        add_prologue_back = findViewById(R.id.add_prologue_back);
        add_prologue_title = findViewById(R.id.add_prologue_title);
        add_prologue_edittext = findViewById(R.id.add_prologue_edittext);
        add_prologue_save = findViewById(R.id.add_prologue_save);

        add_prologue_type = findViewById(R.id.add_prologue_type);
        add_prologue_status = findViewById(R.id.add_prologue_status);
        add_prologue_inputnum = findViewById(R.id.add_prologue_inputnum);

        add_prologue_sound_start = findViewById(R.id.add_prologue_sound_start);
        add_prologue_sound_stop = findViewById(R.id.add_prologue_sound_stop);
        add_prologue_sound_ai = findViewById(R.id.add_prologue_sound_ai);
        add_prologue_sound_local = findViewById(R.id.add_prologue_sound_local);
        add_prologue_sound_listen = findViewById(R.id.add_prologue_sound_listen);

        add_prologue_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //试听
        add_prologue_sound_listen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!FileUtils.getFileExist(getApplicationContext(),prologueModel.getPrologueAudio())){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"音频文件不存在！");
                    return;
                }
                if(PlayStatus == 0){
                    //开始播放
                    PlayStatus = 1;
                    add_prologue_sound_listen.setText("停止试听");
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(prologueModel.getPrologueAudio()));
                        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mediaPlayer) {
                                mediaPlayer.release();
                                PlayStatus = 0;
                                add_prologue_sound_listen.setText("试听");
                            }
                        });
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else{
                    //结束播放
                    add_prologue_sound_listen.setText("试听");
                    PlayStatus = 0;
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
            }
        });
        //开始录音
        add_prologue_sound_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【麦克风】权限！");
                    startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                    return;
                }
                //文件路径
                String outputFile = fileDir+"/luyin_"+ DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp3";
                mediaRecorder = new MediaRecorder();
                mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
                mediaRecorder.setOutputFile(outputFile);
                try {
                    mediaRecorder.prepare();
                    mediaRecorder.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //回答音频
                prologueModel.setPrologueAudio(outputFile);
                //【开始录音】不可点击和隐藏
                add_prologue_sound_start.setEnabled(false);
                add_prologue_sound_start.setVisibility(View.INVISIBLE);
                //【停止录音】可点击和显示
                add_prologue_sound_stop.setEnabled(true);
                add_prologue_sound_stop.setVisibility(View.VISIBLE);
                //【试听】不可点击和隐藏
                add_prologue_sound_listen.setEnabled(false);
                add_prologue_sound_listen.setVisibility(View.INVISIBLE);
            }
        });
        //停止录音
        add_prologue_sound_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mediaRecorder != null){
                    mediaRecorder.stop();
                    mediaRecorder.release();
                    mediaRecorder = null;
                }
                //【开始录音】可点击和显示
                add_prologue_sound_start.setEnabled(true);
                add_prologue_sound_start.setVisibility(View.VISIBLE);
                //【停止录音】不可点击和隐藏
                add_prologue_sound_stop.setEnabled(false);
                add_prologue_sound_stop.setVisibility(View.INVISIBLE);
                //【试听】可点击和显示
                add_prologue_sound_listen.setEnabled(true);
                add_prologue_sound_listen.setVisibility(View.VISIBLE);

                //合成方式 0.暂无 1.录音 2.AI合成 3.本地音频
                prologueModel.setPrologueType(1);
                //合成状态 0.暂无 1.已录音 2.已合成 3.已选择
                prologueModel.setPrologueState(1);

                add_prologue_type.setText(GetUtil.voiceType(prologueModel.getPrologueType()));
                add_prologue_status.setText(GetUtil.voiceState(prologueModel.getPrologueState()));
            }
        });
        //音频合成
        add_prologue_sound_ai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String answer = add_prologue_edittext.getText().toString();
                if(answer.isEmpty()){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请填写关键词！");
                    return;
                }
                if(userModel.getAliyunAccessKeyID().isEmpty() || userModel.getAliyunAppkey().isEmpty() || userModel.getAliyunAccessKeySecret().isEmpty()){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请先配置阿里云密钥！");
                    return;
                }
                if(userModel.getAliyunVoiceSelect().isEmpty() || userModel.getAliyunFontName().isEmpty()){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请选择保存阿里云音色！");
                    return;
                }
                //文件路径
                String outputFile = fileDir+"/ai_"+DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp3";

                //实例化tts
                if(GetUtil.getUtf8CharsNum(answer) > 300){
                    ToastUtils.Setinfo(getApplicationContext(),"文本长度大于300字符",2);
                    return ;
                }
                //语音合成
                AliyunTtsUtil ttsUtil = new AliyunTtsUtil(userModel.getAliyunAppkey(),userModel.getAliyunAccessKeyID(),userModel.getAliyunAccessKeySecret());
                //文本、保存文件名
                ttsUtil.postRequest(getApplicationContext(),answer,outputFile);
                //【试听】可点击和显示
                add_prologue_sound_listen.setEnabled(true);
                add_prologue_sound_listen.setVisibility(View.VISIBLE);

                //合成方式 0.暂无 1.录音 2.AI合成 3.本地音频
                prologueModel.setPrologueType(2);
                //合成状态 0.暂无 1.已录音 2.已合成 3.已选择
                prologueModel.setPrologueState(2);
                //回答音频
                prologueModel.setPrologueAudio(outputFile);

                add_prologue_type.setText(GetUtil.voiceType(prologueModel.getPrologueType()));
                add_prologue_status.setText(GetUtil.voiceState(prologueModel.getPrologueState()));
            }
        });
        //选择本地音频
        add_prologue_sound_local.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), AudioFileListActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        //回复文本编辑
        add_prologue_edittext.addTextChangedListener(new TextWatcher() {
            private String temp;
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before,int count) {
                temp = s.toString();
                add_prologue_inputnum.setText(String.valueOf(temp.length()));
            }
            @Override
            public void afterTextChanged(Editable s) {
                temp = s.toString();
                if (!TextUtils.isEmpty(temp)) {
                    String limitSubstring = GetUtil.getLimitSubString300(temp);	//limitSubstring是UTF-8编码计算后的字符串
                    if (!TextUtils.isEmpty(limitSubstring)) {
                        if (!limitSubstring.equals(temp)) {
                            add_prologue_edittext.setText(limitSubstring);
                            add_prologue_edittext.setSelection(limitSubstring.length());
                        }
                        prologueModel.setPrologueTxt(add_prologue_edittext.getText().toString());
                    }
                }
            }
        });
        //保存
        add_prologue_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(prologueModel.getPrologueAudio().isEmpty()){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请生成或者选择音频！");
                    return;
                }
                PrologueListDatabase prologueDb = new PrologueListDatabase(getApplicationContext());
                if(DataType == 0){
                    prologueDb.insertData(prologueModel);
                }else{
                    prologueDb.updateData(prologueModel);
                }
                ToastUtils.Setinfo(getApplicationContext(),"保存成功",1);
                finish();
            }
        });
        UserDatabase userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();

        fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)+"/zhiboMusic";
        File folder = new File(fileDir);
        if (!folder.exists()) {
            if (folder.mkdirs()) {
                SetListMyValue();
            }else{
                // 文件夹创建失败
                ToastUtils.Setinfo(getApplicationContext(),"无法创建文件夹！",2);
            }
        }else{
            SetListMyValue();
        }
    }

    private void SetListMyValue() {
        DataType = getIntent().getIntExtra("type",0);
        if(DataType == 1){
            prologueModel = (PrologueModel) getIntent().getSerializableExtra("data");
            add_prologue_title.setText("编辑开场白");
            add_prologue_edittext.setText(prologueModel.getPrologueTxt());
            //【试听】可点击和显示
            add_prologue_sound_listen.setEnabled(true);
            add_prologue_sound_listen.setVisibility(View.VISIBLE);
        }else{
            prologueModel = new PrologueModel("",0,0,"");
        }
        add_prologue_inputnum.setText(String.valueOf(prologueModel.getPrologueTxt().length()));
        add_prologue_type.setText(GetUtil.voiceType(prologueModel.getPrologueType()));
        add_prologue_status.setText(GetUtil.voiceState(prologueModel.getPrologueState()));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
            if (data != null) {
                AudioFileModel model = (AudioFileModel) data.getSerializableExtra("model");
                //音频路径
                prologueModel.setPrologueAudio(model.getUrl());
                //合成方式 0.暂无 1.录音 2.AI合成 3.本地音频
                prologueModel.setPrologueType(3);
                //合成状态 0.暂无 1.已录音 2.已合成 3.已选择
                prologueModel.setPrologueState(3);

                //【试听】可点击和显示
                add_prologue_sound_listen.setEnabled(true);
                add_prologue_sound_listen.setVisibility(View.VISIBLE);

                add_prologue_type.setText(GetUtil.voiceType(prologueModel.getPrologueType()));
                add_prologue_status.setText(GetUtil.voiceState(prologueModel.getPrologueState()));
            }
        }
    }

    //任意写一个方法，给这个方法一个@Subscribe注解，参数类型可以自定义，但是一定要与你发出的类型相同
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(TtsMessageEvent ttsMessageEvent){
        switch (ttsMessageEvent.getNumber()) {
            case 1://正确
                ToastUtils.Setinfo(this,ttsMessageEvent.getMessage(),1);
                break;
            case 2://异常
                ToastUtils.Setinfo(this,ttsMessageEvent.getMessage(),2);
                break;
            case 3://底部toast
                ToastBottomUtils.Setinfo(this,ttsMessageEvent.getMessage());
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);
        // 释放MediaPlayer资源
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        // 释放mediaRecorder资源
        if (mediaRecorder != null) {
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }
}